package br.com.PrimeFaces.persistencia.jpa.dao;

import br.com.PrimeFaces.persistencia.jpa.util.JPAUtil;

import java.io.Serializable;
import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.Query;

/**
 *
 * @author Paulo
 */
public abstract class GenericDAO<T, ID extends Serializable> {

    public GenericDAO() {
    }

    public abstract Class<T> getEntityClass();

    public T inserirEditar(T entidade) {

        return JPAUtil.getEntityManager().merge(entidade);

    }

    public void deletar(T entidade) throws Exception {

        JPAUtil.getEntityManager().remove(entidade);

    }

    public T buscar(ID id) throws Exception {

        return JPAUtil.getEntityManager().find(getEntityClass(), id);

    }

    public T buscarOnde(String filtro) throws Exception {
        Query dynaQuery = JPAUtil.getEntityManager().createQuery("FROM " + getEntityClass().getName() + " WHERE " + filtro);
        try {
            return (T)dynaQuery.getSingleResult();
        } catch (NoResultException n) {
            return null;
        }
    }

    public List<T> listar() throws Exception {

        Query dynaQuery = JPAUtil.getEntityManager().createQuery("FROM " + getEntityClass().getName());
        return dynaQuery.getResultList();
    }    

    
    public List<T> listarOnde(String filtro) throws Exception {
        Query dynaQuery = JPAUtil.getEntityManager().createQuery("FROM " + getEntityClass().getName() + " WHERE " + filtro);
        try {
            return (List<T>)dynaQuery.getResultList();
        } catch (NoResultException n) {
            return null;
        }
    }    
}
